import custom.Config;
import org.atmosphere.config.service.Disconnect;
import org.atmosphere.config.service.Heartbeat;
import org.atmosphere.config.service.ManagedService;
import org.atmosphere.config.service.Ready;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResourceEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

import static org.atmosphere.cpr.ApplicationConfig.MAX_INACTIVE;

/**
 * Created by alex on 15-1-13.
 */
@Config
@ManagedService(path = "/chat",
        atmosphereConfig = MAX_INACTIVE + "=120000"
)
public class Chat {

    private final Logger logger = LoggerFactory.getLogger(Chat.class);
    
    @Heartbeat
    public void onHearbeat(final AtmosphereResourceEvent event){
        
        logger.info("Heartbeat send by {}",event.getResource());
    }
    
    @Ready
    public void onReady(final AtmosphereResource resource) {
        logger.info("Browser {} connected", resource.uuid());

    }
    
    @Disconnect
    public void onDisconnect(AtmosphereResourceEvent event){
        if(event.isCancelled()){
            logger.info("Browser {} unexpectedly disconnected",event.getResource().uuid());
        } else if(event.isClosedByClient()){
            logger.info("Browser {} closed the connected",event.getResource().uuid());            
        }
    }
    
    @org.atmosphere.config.service.Message(encoders = {JacksonEncoders.class}, decoders = {JacksonDecoder.class})
    public Message onMessage(Message message) throws IOException{
        logger.info("{} just send {}",message.getAuthor(),message.getMessage());
        return message;
    }
}
